<script setup lang="ts">
import DictFormPanel from './DictFormPanel.vue'
import DictTreeRightMenu from './DictTreeRightMenu.vue'
import { DictApi } from '@/apis'
import { useConfirm, useRequest } from '@/hooks'
import type { DictType } from '@/apis/system/dict'

const emit = defineEmits<{
  (e: 'select', dictId: string, type: DictType): void
}>()

const type = ref<DictType>('custom')

const onTreeNodeSelect = (key: string) => {
  emit('select', key, type.value)
}

// 自定义字典
const {
  loading: customDataLoading,
  response: customData,
  refresh: customDataRefresh,
} = useRequest(() => DictApi.listDict({}).then(res =>
  res.map((item) => {
    return {
      id: item.id,
      code: item.code,
      title: `${item.name}(${item.code})`,
    }
  }),
))

// 系统枚举字典
const {
  loading: systemDataLoading,
  response: systemData,
} = useRequest(() => DictApi.listEnumDict().then(res =>
  res.map((item) => {
    return {
      id: item.id,
      code: item.code,
      title: item.name ? `${item.name}(${item.code})` : item.code,
    }
  }),
))

// 新增
const DictFormPanelRef = ref<InstanceType<typeof DictFormPanel>>()
const onAdd = () => {
  DictFormPanelRef.value?.create()
}

// 右键菜单
const onMenuItemClick = (mode: string, node: DictApi.DictResp) => {
  if (mode === 'update') {
    DictFormPanelRef.value?.edit(node.id)
  } else if (mode === 'delete') {
    useConfirm(() => DictApi.removeDict(node.id), () => {
      customDataRefresh()
    })
  }
}
</script>

<template>
  <div class="h-full flex-y">
    <a-radio-group v-model="type" type="button" style="margin-bottom: 5px; width: 100%;">
      <a-radio value="custom" style="width: 50%;" class="text-center">
        自定义字典
      </a-radio>
      <a-radio value="system" style="width: 50%;" class="text-center">
        枚举字典
      </a-radio>
    </a-radio-group>
    <ListTree
      v-if="type === 'custom'"
      class="flex-1"
      :loading="customDataLoading"
      :data="customData"
      @select="onTreeNodeSelect"
    >
      <template #action="nodeData">
        <DictTreeRightMenu
          v-permission="['system:dict:write']"
          :data="nodeData"
          @on-menu-item-click="onMenuItemClick"
        />
      </template>
    </ListTree>
    <ListTree
      v-else
      :loading="systemDataLoading"
      :data="systemData"
      @select="onTreeNodeSelect"
    />
    <div v-if="type === 'custom'" class="mt-10px">
      <a-button v-permission="['system:dict:manage']" type="primary" style="width: 100%" @click="onAdd">
        <template #icon>
          <icon-plus />
        </template>
        <span>新增</span>
      </a-button>
    </div>
  </div>
  <DictFormPanel ref="DictFormPanelRef" @change="customDataRefresh" />
</template>

<style lang="less" scoped>
</style>
